package com.wonderful.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.wonderful.common.constant.AuthServerConstant;
import com.wonderful.common.enums.BizCodeEnum;
import com.wonderful.common.utils.R;
import com.wonderful.common.vo.MemberRespVo;
import com.wonderful.mall.auth.feign.MemberFeignService;
import com.wonderful.mall.auth.feign.ThirdPartyFeignService;
import com.wonderful.mall.auth.vo.UserLoginVo;
import com.wonderful.mall.auth.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Resource
    ThirdPartyFeignService thirdPartyFeignService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("mobile") String mobile) {
        String s = stringRedisTemplate.opsForValue().get("AuthServerConstant.SMS_CODE_CACHE_PREFIX+mobile");
        if (!StringUtils.isEmpty(s)) {
            long l = Long.parseLong(s.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //60秒内不能再发送
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
        thirdPartyFeignService.sendCode(mobile, code);
        //redis缓存验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + mobile, code, 5, TimeUnit.MINUTES);
        return R.ok();
    }

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, fieldError -> {
                if (fieldError.getDefaultMessage() != null) {
                    return fieldError.getDefaultMessage();
                } else {
                    return "";
                }
            }));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.wonderfulmall.com/reg.html";
        }
        String code = vo.getCode();
        //从缓存中获取这个手机号
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getMobile());
        if (!StringUtils.isEmpty(s)){
            //验证码相同
            if (code.equals(s.split("_")[0])){
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getMobile());
                R r = memberFeignService.register(vo);
                if (r.getCode()==0){
                    return "redirect:http://auth.wonderfulmall.com/login.html";
                }else {
                    Map<String,String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.wonderfulmall.com/reg.html";
                }
            } else {
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.wonderfulmall.com/reg.html";
            }
        }else {
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.wonderfulmall.com/reg.html";
        }
    }
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        if(session.getAttribute(AuthServerConstant.LOGIN_USER)==null)
            return "login";
        return "redirect:http://wonderfulmall.com";
    }
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session){
        R login = memberFeignService.login(vo);
        if (login.getCode()==0){
            MemberRespVo data = login.getData(new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://wonderfulmall.com";
        }
        Map<String,String> errors = new HashMap<>();
        errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
        attributes.addFlashAttribute("errors",errors);
        return "redirect:http://auth.wonderfulmall.com/login.html";
    }
}
